<template>
  <div class="modern-message-center">
    <!-- 顶部横幅 -->
    <div class="message-hero">
      <div class="hero-background">
        <div class="hero-shape shape-1" />
        <div class="hero-shape shape-2" />
        <div class="hero-shape shape-3" />
      </div>
      <div class="hero-content">
        <div class="hero-left">
          <h1 class="hero-title">
            <el-icon class="title-icon"><ChatDotRound /></el-icon>
            消息中心
          </h1>
          <p class="hero-subtitle">随时掌握最新动态</p>
        </div>
        <div v-if="stats.totalUnreadCount > 0" class="hero-stats">
          <div class="stat-badge">
            <span class="badge-number">{{ stats.totalUnreadCount }}</span>
            <span class="badge-text">条未读</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 选项卡导航 -->
    <div class="tabs-wrapper">
      <el-tabs
        v-model="activeTab"
        class="modern-tabs"
        @tab-click="handleTabClick"
      >
        <!-- 公告选项卡 -->
        <el-tab-pane name="announcement">
          <template #label>
            <div class="tab-label">
              <el-icon class="tab-icon"><BellFilled /></el-icon>
              <span class="tab-text">系统公告</span>
              <span v-if="announcementUnreadCount > 0" class="tab-count">
                {{ announcementUnreadCount }}
              </span>
            </div>
          </template>
          <div class="tab-content-wrapper">
            <AnnouncementList
              ref="announcementListRef"
              @update-count="handleUpdateAnnouncementCount"
            />
          </div>
        </el-tab-pane>

        <!-- 互动消息选项卡 -->
        <el-tab-pane name="interactions">
          <template #label>
            <div class="tab-label">
              <el-icon class="tab-icon"><StarFilled /></el-icon>
              <span class="tab-text">互动消息</span>
              <span v-if="interactionsUnreadCount > 0" class="tab-count">
                {{ interactionsUnreadCount }}
              </span>
            </div>
          </template>

          <!-- 筛选区域 -->
          <div class="filter-section">
            <div class="filter-container">
              <div class="filter-group">
                <label class="filter-label">通知类型</label>
                <div class="filter-buttons">
                  <el-button
                    :type="queryParams.type === '' ? 'primary' : ''"
                    size="default"
                    @click="handleFilterChange('type', '')"
                  >
                    全部
                  </el-button>
                  <el-button
                    :type="queryParams.type === 'LIKE' ? 'primary' : ''"
                    size="default"
                    @click="handleFilterChange('type', 'LIKE')"
                  >
                    <el-icon><StarFilled /></el-icon>
                    <span>点赞</span>
                    <span v-if="stats.unreadLikeCount" class="count-badge">
                      {{ stats.unreadLikeCount }}
                    </span>
                  </el-button>
                  <el-button
                    :type="queryParams.type === 'FOLLOW' ? 'primary' : ''"
                    size="default"
                    @click="handleFilterChange('type', 'FOLLOW')"
                  >
                    <el-icon><UserFilled /></el-icon>
                    <span>关注</span>
                    <span v-if="stats.unreadFollowCount" class="count-badge">
                      {{ stats.unreadFollowCount }}
                    </span>
                  </el-button>
                </div>
              </div>

              <div class="filter-group">
                <label class="filter-label">阅读状态</label>
                <div class="filter-buttons">
                  <el-button
                    :type="queryParams.isRead === null ? 'primary' : ''"
                    size="default"
                    @click="handleFilterChange('isRead', null)"
                  >
                    全部
                  </el-button>
                  <el-button
                    :type="queryParams.isRead === 0 ? 'primary' : ''"
                    size="default"
                    @click="handleFilterChange('isRead', 0)"
                  >
                    <span class="status-dot unread" />
                    未读
                  </el-button>
                  <el-button
                    :type="queryParams.isRead === 1 ? 'primary' : ''"
                    size="default"
                    @click="handleFilterChange('isRead', 1)"
                  >
                    <span class="status-dot read" />
                    已读
                  </el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 批量操作工具栏 -->
          <div v-if="notificationGroups.length > 0" class="batch-actions-bar">
            <div class="actions-left">
              <template v-if="!selectionMode">
                <span class="result-count">
                  共 <strong>{{ total }}</strong> 条通知
                  <template v-if="interactionsUnreadCount > 0">
                    ，<strong class="unread-count">{{
                      interactionsUnreadCount
                    }}</strong>
                    条未读
                  </template>
                </span>
              </template>
              <template v-else>
                <el-checkbox
                  v-model="selectAll"
                  :indeterminate="isIndeterminate"
                  @change="handleSelectAll"
                >
                  全选
                </el-checkbox>
                <span class="selected-count">
                  已选中 <strong>{{ selectedGroups.length }}</strong> 条
                </span>
              </template>
            </div>
            <div class="actions-right">
              <template v-if="!selectionMode">
                <el-button
                  v-if="interactionsUnreadCount > 0"
                  type="primary"
                  size="default"
                  :icon="Check"
                  @click="handleMarkAllAsRead"
                >
                  全部标为已读
                </el-button>
                <el-button size="default" @click="enterSelectionMode">
                  选择
                </el-button>
              </template>
              <template v-else>
                <el-button
                  type="danger"
                  size="default"
                  :disabled="selectedGroups.length === 0"
                  @click="handleBatchDelete"
                >
                  删除选中({{ selectedGroups.length }})
                </el-button>
                <el-button size="default" @click="exitSelectionMode">
                  取消
                </el-button>
              </template>
            </div>
          </div>

          <!-- 通知列表 - 列表式布局 -->
          <div v-loading="loading" class="notification-list">
            <!-- 通知项容器 -->
            <div
              v-for="group in notificationGroups"
              :key="group.groupKey"
              class="notification-item-wrapper"
            >
              <!-- 通知主行 -->
              <div
                class="notification-item"
                :class="{
                  'is-unread': group.unreadCount > 0,
                  'selection-mode': selectionMode
                }"
                @click="!selectionMode && handleExpandDetails(group)"
              >
                <!-- 选择框 -->
                <div v-if="selectionMode" class="item-checkbox" @click.stop>
                  <el-checkbox
                    :model-value="selectedGroups.includes(group.groupKey)"
                    @change="toggleSelect(group.groupKey)"
                  />
                </div>

                <!-- 左侧图标区 -->
                <div class="item-icon">
                  <div
                    class="icon-wrapper"
                    :class="`icon-${group.type.toLowerCase()}`"
                  >
                    <el-icon>
                      <component
                        :is="
                          group.type === 'LIKE'
                            ? StarFilled
                            : group.type === 'COMMENT'
                              ? ChatDotRound
                              : group.type === 'REPLY'
                                ? Comment
                                : group.type === 'FOLLOW'
                                  ? UserFilled
                                  : Setting
                        "
                      />
                    </el-icon>
                  </div>
                  <!-- 未读红点 -->
                  <span v-if="group.unreadCount > 0" class="unread-dot" />
                </div>

                <!-- 中间内容区域 -->
                <div class="item-content">
                  <!-- 头像 + 标题 -->
                  <div class="content-header">
                    <!-- 头像组 -->
                    <div class="avatar-group">
                      <el-avatar
                        v-for="(sender, index) in (group.senders || []).slice(
                          0,
                          3
                        )"
                        :key="sender.userId"
                        :src="formatAvatarUrl(sender.avatar)"
                        :size="24"
                        :style="{
                          zIndex: 3 - index,
                          marginLeft: index > 0 ? '-8px' : '0'
                        }"
                      >
                        {{ sender.nickName?.charAt(0) }}
                      </el-avatar>
                    </div>

                    <!-- 标题文字 -->
                    <span
                      class="content-title"
                      :class="{ 'is-unread': group.unreadCount > 0 }"
                    >
                      {{ group.aggregatedTitle }}
                    </span>

                    <!-- 数量标记 -->
                    <span v-if="group.count > 1" class="count-badge">
                      {{ group.count }}
                    </span>
                  </div>

                  <!-- 评论/回复类型显示提示 -->
                  <div
                    v-if="
                      (group.type === 'COMMENT' || group.type === 'REPLY') &&
                      group.target?.url
                    "
                    class="action-hint"
                    @click.stop="handleJumpToReply(group)"
                  >
                    <el-icon><Right /></el-icon>
                    <span>点击查看并回复</span>
                  </div>
                </div>

                <!-- 右侧信息区域 -->
                <div class="item-aside" @click.stop>
                  <!-- 时间 -->
                  <span class="item-time">{{
                    formatTime(group.latestTime)
                  }}</span>

                  <!-- 快捷操作 -->
                  <div v-if="!selectionMode" class="item-actions">
                    <el-button
                      v-if="group.unreadCount > 0"
                      size="small"
                      text
                      type="primary"
                      title="标记已读"
                      @click.stop="handleMarkGroupAsRead(group)"
                    >
                      <el-icon><Check /></el-icon>
                    </el-button>
                    <span v-else class="read-text">已读</span>
                    <el-popconfirm
                      :title="`确定要删除这 ${group.count} 条通知吗?`"
                      confirm-button-text="确定"
                      cancel-button-text="取消"
                      @confirm="confirmDeleteGroup(group)"
                    >
                      <template #reference>
                        <el-button size="small" text type="danger" title="删除">
                          <el-icon><Delete /></el-icon>
                        </el-button>
                      </template>
                    </el-popconfirm>
                    <el-button
                      size="small"
                      text
                      title="展开/收起"
                      @click.stop="handleExpandDetails(group)"
                    >
                      <el-icon>
                        <component
                          :is="
                            expandedGroups[group.groupKey] ? ArrowUp : ArrowDown
                          "
                        />
                      </el-icon>
                    </el-button>
                  </div>
                </div>
              </div>

              <!-- 展开的详情列表(位于下方) -->
              <transition name="slide-fade">
                <div
                  v-if="expandedGroups[group.groupKey]"
                  v-loading="detailLoadingMap[group.groupKey]"
                  class="group-details"
                >
                  <!-- 用户列表标题 -->
                  <div class="details-header">
                    <span class="details-title">互动记录</span>
                    <span class="details-count">{{ group.count }} 条</span>
                  </div>

                  <!-- 用户列表 -->
                  <div class="user-list">
                    <div
                      v-for="detail in groupDetailsMap[group.groupKey]"
                      :key="detail.id"
                      class="user-item"
                      :class="{ 'is-unread': !detail.isRead }"
                    >
                      <div class="item-left">
                        <el-avatar
                          :src="formatAvatarUrl(detail.sender?.avatar)"
                          :size="36"
                          class="user-avatar"
                        >
                          {{ detail.sender?.nickName?.charAt(0) }}
                        </el-avatar>

                        <div class="message-user-content">
                          <div class="user-header">
                            <span class="user-name">{{
                              detail.sender?.nickName
                            }}</span>
                            <span class="user-action">{{
                              detail.actionText
                            }}</span>
                            <span class="meta-time">{{
                              formatTime(detail.createTime)
                            }}</span>
                            <el-tag
                              v-if="!detail.isRead"
                              type="danger"
                              size="small"
                              effect="dark"
                            >
                              未读
                            </el-tag>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </transition>
            </div>

            <!-- 空状态 -->
            <el-empty
              v-if="!loading && notificationGroups.length === 0"
              description="暂无通知"
            />
          </div>

          <!-- 分页 -->
          <div class="notification-pagination">
            <el-pagination
              v-model:current-page="queryParams.current"
              v-model:page-size="queryParams.size"
              :total="total"
              :page-sizes="[10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="handlePageChange"
              @size-change="handleSizeChange"
            />
          </div>
        </el-tab-pane>

        <!-- 评论和回复选项卡 -->
        <el-tab-pane name="comments">
          <template #label>
            <div class="tab-label">
              <el-icon class="tab-icon"><ChatDotRound /></el-icon>
              <span class="tab-text">评论和回复</span>
              <span v-if="commentsUnreadCount > 0" class="tab-count">
                {{ commentsUnreadCount }}
              </span>
            </div>
          </template>
          <div class="tab-content-wrapper">
            <!-- 🔑 使用 v-if 懒加载，只有访问过的标签页才渲染组件 -->
            <CommentReplyList
              v-if="visitedTabs.has('comments')"
              v-show="activeTab === 'comments'"
              ref="commentReplyListRef"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 分组详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="currentGroup?.aggregatedTitle"
      width="800px"
    >
      <div v-loading="detailLoading" class="group-details">
        <div
          v-for="notification in groupDetails"
          :key="notification.id"
          class="notification-detail-item"
        >
          <el-avatar
            :src="formatAvatarUrl(notification.sender?.avatar)"
            size="small"
          >
            {{ notification.sender?.nickName?.charAt(0) }}
          </el-avatar>
          <div class="detail-content">
            <div class="detail-header">
              <span class="sender-name">{{
                notification.sender?.nickName
              }}</span>
              <span class="action-text">{{ notification.actionText }}</span>
              <span class="detail-time">{{
                formatTime(notification.createTime)
              }}</span>
            </div>
            <!-- 显示文章标题或评论内容 -->
            <div v-if="notification.articleInfo" class="detail-target">
              {{ notification.articleInfo.title }}
            </div>
            <div v-else-if="notification.commentDetail" class="detail-target">
              {{ notification.commentDetail.content }}
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleMarkGroupAsRead(currentGroup)">
          全部标为已读
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  onMounted,
  onBeforeUnmount,
  computed,
  nextTick
} from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import {
  ChatDotRound,
  BellFilled,
  Message,
  StarFilled,
  UserFilled,
  Setting,
  Check,
  ArrowUp,
  ArrowDown,
  Star,
  Comment,
  Delete,
  Right,
  Document
} from "@element-plus/icons-vue";
import {
  getGroupedNotifications,
  getGroupDetails,
  markGroupAsRead,
  markAllNotificationsAsReadApi,
  batchMarkNotificationsAsReadApi,
  deleteNotificationApi,
  batchDeleteNotificationsApi,
  NotificationType,
  type GroupedNotification,
  type NotificationDetail
} from "@/api/notification";
import { formatAvatarUrl } from "@/utils/avatar";
import { notificationService } from "@/services/notificationService";
import { useUserAuthStore } from "@/store/modules/userAuth";
import AnnouncementList from "./components/AnnouncementList.vue";
import CommentReplyList from "./components/CommentReplyList.vue";

// 路由实例
const router = useRouter();
const route = useRoute();

// 用户认证 store
const userAuthStore = useUserAuthStore();

// 从 URL 查询参数或 localStorage 获取初始标签页
const getInitialTab = (): string => {
  // 优先使用 URL 查询参数
  const tabFromQuery = route.query.tab as string;
  if (
    tabFromQuery &&
    ["announcement", "interactions", "comments"].includes(tabFromQuery)
  ) {
    return tabFromQuery;
  }

  // 🔑 如果是从消息铃铛进入（from=notification），默认显示系统公告，忽略 localStorage
  const fromQuery = route.query.from as string;
  if (fromQuery === "notification") {
    return "announcement";
  }

  // 其次使用 localStorage
  const tabFromStorage = localStorage.getItem("message-center-active-tab");
  if (
    tabFromStorage &&
    ["announcement", "interactions", "comments"].includes(tabFromStorage)
  ) {
    return tabFromStorage;
  }

  // 默认返回公告
  return "announcement";
};

// 响应式数据
const activeTab = ref(getInitialTab());
const loading = ref(false);
const detailLoading = ref(false);
const detailDialogVisible = ref(false);
const notificationGroups = ref<GroupedNotification[]>([]);
const groupDetails = ref<NotificationDetail[]>([]);
const currentGroup = ref<GroupedNotification | null>(null);
const total = ref(0);

// 分组列表请求去重相关
const isGroupedRequesting = ref(false); // 同步锁：标记是否正在请求中（防止毫秒级并发调用）
const isInitialized = ref(false); // 标记是否已完成初始化加载
const announcementUnreadCount = ref(0);
const announcementListRef = ref();
const commentReplyListRef = ref();

// 展开状态管理
const expandedGroups = ref<Record<string, boolean>>({});
const groupDetailsMap = ref<Record<string, NotificationDetail[]>>({});
const detailLoadingMap = ref<Record<string, boolean>>({});

// 选择模式管理
const selectionMode = ref(false);
const selectedGroups = ref<string[]>([]);
const selectAll = ref(false);
const isIndeterminate = computed(() => {
  const len = selectedGroups.value.length;
  return len > 0 && len < notificationGroups.value.length;
});

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 20,
  type: "",
  isRead: null
});

// 使用单例服务的统计数据
const statsRef = notificationService.getStatsRef();
const stats = computed(() => {
  return (
    statsRef.value || {
      totalUnreadCount: 0,
      unreadLikeCount: 0,
      unreadCommentCount: 0,
      unreadReplyCount: 0,
      unreadFollowCount: 0,
      hasUnread: false
    }
  );
});

// 互动消息未读数（点赞 + 关注）
const interactionsUnreadCount = computed(() => {
  return (
    (stats.value.unreadLikeCount || 0) + (stats.value.unreadFollowCount || 0)
  );
});

// 评论和回复未读数（评论 + 回复）
const commentsUnreadCount = computed(() => {
  return (
    (stats.value.unreadCommentCount || 0) + (stats.value.unreadReplyCount || 0)
  );
});

// 加载通知列表（分组）
const loadNotifications = async () => {
  // 🔑 同步锁：最高优先级的并发去重，立即检查并设置标志位
  if (isGroupedRequesting.value) {
    console.log(
      "⏭️ 互动消息分组列表已有请求正在进行中（同步锁），跳过本次调用"
    );
    return;
  }
  isGroupedRequesting.value = true;

  try {
    // 并发去重
    if (loading.value) {
      console.log("⏭️ 互动消息分组列表正在加载中，跳过重复请求");
      return;
    }

    loading.value = true;
    try {
      const response = await getGroupedNotifications(queryParams);
      if (response.code === 200) {
        notificationGroups.value = response.data.records;
        total.value = response.data.total;
      }
    } catch (error) {
      ElMessage.error("加载通知失败");
      console.error(error);
    } finally {
      loading.value = false;
    }
  } finally {
    // 无论成功失败，最终都要释放同步锁
    isGroupedRequesting.value = false;
  }
};

// 加载统计数据
const loadStats = async () => {
  await notificationService.loadStats();
};

// 清理 URL，确保是客户端路径
const sanitizeUrl = (url: string): string => {
  if (!url) return url;

  let cleanUrl = url;

  // 如果是完整的 URL(包含协议),尝试提取路径部分
  try {
    if (url.startsWith("http://") || url.startsWith("https://")) {
      const urlObj = new URL(url);
      cleanUrl = urlObj.pathname + urlObj.search + urlObj.hash;
      console.log("🧹 清理完整 URL:", url, "-> ", cleanUrl);
    }
  } catch (e) {
    console.warn("⚠️ 无法解析 URL:", url, e);
  }

  // 将 /article/ 路径转换为 /user/article/ (用户端路径)
  if (cleanUrl.startsWith("/article/")) {
    cleanUrl = "/user" + cleanUrl;
    console.log("🔄 转换路径:", url, "-> ", cleanUrl);
  }

  return cleanUrl;
};

// 切换分组展开/收起
const toggleGroupExpand = async (group: GroupedNotification) => {
  console.log("👆 点击通知卡片:", group);
  console.log("🔗 target 信息:", group.target);
  console.log("📍 原始 target.url:", group.target?.url);

  // 如果有 target.url，优先跳转
  if (group.target?.url) {
    const cleanUrl = sanitizeUrl(group.target.url);
    console.log("✅ 有 URL，清理后的 URL:", cleanUrl);
    console.log("🔑 当前登录状态:", {
      isLoggedIn: userAuthStore.isLoggedIn,
      userId: userAuthStore.userId,
      token: userAuthStore.token ? "exists" : "null"
    });
    console.log("🚀 开始跳转...");

    try {
      await router.push(cleanUrl);
      console.log("✅ 跳转成功");
    } catch (error) {
      console.error("❌ 跳转失败:", error);
      ElMessage.error("跳转失败，请稍后再试");
    }
    return;
  }

  // 如果没有 URL，则展开/收起详情
  console.log("⚠️ 没有 target.url，切换展开/收起状态");

  const groupKey = group.groupKey;

  // 如果已展开，则收起
  if (expandedGroups.value[groupKey]) {
    expandedGroups.value[groupKey] = false;
    return;
  }

  // 如果未展开，则展开并加载详情
  expandedGroups.value[groupKey] = true;

  // 如果已经加载过详情，直接显示
  if (groupDetailsMap.value[groupKey]) {
    return;
  }

  // 加载详情
  detailLoadingMap.value[groupKey] = true;
  try {
    const response = await getGroupDetails({
      type: group.type,
      targetType: group.targetType,
      targetId: group.targetId
    });
    if (response.code === 200) {
      groupDetailsMap.value[groupKey] = response.data;
    }
  } catch (error) {
    ElMessage.error("加载详情失败");
    console.error(error);
    // 加载失败时收起
    expandedGroups.value[groupKey] = false;
  } finally {
    detailLoadingMap.value[groupKey] = false;
  }
};

// 处理“点击查看并回复”跳转
const handleJumpToReply = async (group: GroupedNotification) => {
  console.log("🚀 点击查看并回复，准备跳转");
  console.log("🔗 target 信息:", group.target);
  console.log("📍 原始 target.url:", group.target?.url);

  if (!group.target?.url) {
    console.warn("⚠️ 没有 target.url，无法跳转");
    ElMessage.warning("该通知暂无跳转链接");
    return;
  }

  const cleanUrl = sanitizeUrl(group.target.url);
  console.log("✅ 清理后的 URL:", cleanUrl);
  console.log("🔑 当前登录状态:", {
    isLoggedIn: userAuthStore.isLoggedIn,
    userId: userAuthStore.userId,
    token: userAuthStore.token ? "exists" : "null"
  });
  console.log("🚀 开始跳转...");

  try {
    await router.push(cleanUrl);
    console.log("✅ 跳转成功");
  } catch (error) {
    console.error("❌ 跳转失败:", error);
    ElMessage.error("跳转失败，请稍后再试");
  }
};

// 处理右侧展开/收起按钮（不进行跳转）
const handleExpandDetails = async (group: GroupedNotification) => {
  console.log("📝 点击展开/收起按钮");

  const groupKey = group.groupKey;

  // 如果已展开，则收起
  if (expandedGroups.value[groupKey]) {
    expandedGroups.value[groupKey] = false;
    return;
  }

  // 如果未展开，则展开并加载详情
  expandedGroups.value[groupKey] = true;

  // 如果已经加载过详情，直接显示
  if (groupDetailsMap.value[groupKey]) {
    return;
  }

  // 加载详情
  detailLoadingMap.value[groupKey] = true;
  try {
    const response = await getGroupDetails({
      type: group.type,
      targetType: group.targetType,
      targetId: group.targetId
    });
    if (response.code === 200) {
      groupDetailsMap.value[groupKey] = response.data;
    }
  } catch (error) {
    ElMessage.error("加载详情失败");
    console.error(error);
    // 加载失败时收起
    expandedGroups.value[groupKey] = false;
  } finally {
    detailLoadingMap.value[groupKey] = false;
  }
};

// 点击分组，查看详情
const handleGroupClick = async group => {
  currentGroup.value = group;
  detailDialogVisible.value = true;
  detailLoading.value = true;

  try {
    const response = await getGroupDetails({
      type: group.type,
      targetType: group.targetType,
      targetId: group.targetId
    });
    if (response.code === 200) {
      groupDetails.value = response.data;
    }
  } catch (error) {
    ElMessage.error("加载详情失败");
    console.error(error);
  } finally {
    detailLoading.value = false;
  }
};

// 批量标记所有通知为已读
const handleMarkAllAsRead = async () => {
  try {
    await ElMessageBox.confirm("确定要将所有通知标记为已读吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const unreadCount = stats.value.totalUnreadCount;
    const response = await markAllNotificationsAsReadApi(
      queryParams.type ? (queryParams.type as NotificationType) : undefined
    );
    if (response.code === 200) {
      ElNotification({
        title: "标记成功",
        message: `已将${queryParams.type ? "当前类型的" : ""}所有通知标记为已读`,
        type: "success",
        duration: 3000,
        position: "top-right"
      });

      // 刷新列表和统计
      await loadNotifications();
      await loadStats();
    }
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("操作失败");
      console.error(error);
    }
  }
};

// 标记分组为已读
const handleMarkGroupAsRead = async group => {
  try {
    // 获取该组的所有通知ID
    const groupKey = group.groupKey;
    let notificationIds: number[] = [];

    // 如果已经加载过详情,从详情中获取ID
    if (groupDetailsMap.value[groupKey]) {
      notificationIds = groupDetailsMap.value[groupKey]
        .filter(d => d.isRead === 0)
        .map(d => d.id);
    } else {
      // 否则先加载详情
      const response = await getGroupDetails({
        type: group.type,
        targetType: group.targetType,
        targetId: group.targetId
      });
      if (response.code === 200) {
        notificationIds = response.data
          .filter(d => d.isRead === 0)
          .map(d => d.id);
      }
    }

    // 批量标记为已读
    if (notificationIds.length > 0) {
      const markResponse =
        await batchMarkNotificationsAsReadApi(notificationIds);
      if (markResponse.code === 200) {
        ElNotification({
          title: "标记成功",
          message: `已将 ${notificationIds.length} 条通知标记为已读`,
          type: "success",
          duration: 3000,
          position: "top-right"
        });

        // 更新本地状态
        group.unreadCount = 0;

        // 如果该分组已展开,更新详情中的已读状态
        if (groupDetailsMap.value[groupKey]) {
          groupDetailsMap.value[groupKey].forEach(detail => {
            detail.isRead = 1;
          });
        }

        // 刷新统计
        await loadStats();
        // 关闭弹窗
        detailDialogVisible.value = false;
      }
    } else {
      ElNotification({
        title: "提示",
        message: "没有未读通知",
        type: "info",
        duration: 2000,
        position: "top-right"
      });
    }
  } catch (error) {
    ElMessage.error("操作失败");
    console.error(error);
  }
};

// 统一的筛选变化处理
const handleFilterChange = (field: string, value: any) => {
  // 🔑 如果还未初始化完成,不触发请求
  if (!isInitialized.value) {
    if (field === "type") {
      queryParams.type = value;
    } else if (field === "isRead") {
      queryParams.isRead = value;
    }
    return;
  }

  if (field === "type") {
    queryParams.type = value;
  } else if (field === "isRead") {
    queryParams.isRead = value;
  }
  queryParams.current = 1;
  loadNotifications();
};

// 筛选类型变化
const handleTypeChange = () => {
  queryParams.current = 1;
  loadNotifications();
};

// 已读状态变化
const handleReadStatusChange = () => {
  queryParams.current = 1;
  loadNotifications();
};

// 分页变化
const handlePageChange = page => {
  queryParams.current = page;
  loadNotifications();
};

const handleSizeChange = size => {
  queryParams.size = size;
  queryParams.current = 1;
  loadNotifications();
};

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return "";

  const now = new Date();
  const noticeTime = new Date(time);
  const diff = now.getTime() - noticeTime.getTime();

  const minutes = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days = Math.floor(diff / 86400000);

  if (minutes < 1) return "刚刚";
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  if (days < 7) return `${days}天前`;

  return time.split(" ")[0]; // 返回日期部分
};

// 获取通知类型标签配置
const getNotificationTypeTag = (type: string) => {
  const typeMap: Record<string, { label: string; type: any; icon: any }> = {
    LIKE: { label: "点赞", type: "warning", icon: StarFilled },
    COMMENT: { label: "评论", type: "primary", icon: ChatDotRound },
    FOLLOW: { label: "关注", type: "success", icon: UserFilled },
    SYSTEM: { label: "系统", type: "info", icon: Setting }
  };
  return typeMap[type] || { label: "通知", type: "info", icon: Message };
};

// 根据通知类型和目标类型格式化标题显示
const formatTargetTitle = (type: string, targetType: string, target: any) => {
  const typeUpper = type.toUpperCase();
  const targetTypeUpper = targetType?.toUpperCase();

  let text = "";

  // 根据通知类型和目标类型生成描述文字
  switch (typeUpper) {
    case "FOLLOW":
      text = "新增粉丝";
      break;
    case "LIKE":
      if (targetTypeUpper === "ARTICLE") {
        text = "点赞了你的文章";
      } else if (targetTypeUpper === "COMMENT") {
        text = "点赞了你的评论";
      } else {
        text = "点赞了你的内容";
      }
      break;
    case "COLLECT":
      if (targetTypeUpper === "ARTICLE") {
        text = "收藏了你的文章";
      } else {
        text = "收藏了你的内容";
      }
      break;
    case "COMMENT":
      if (targetTypeUpper === "ARTICLE") {
        text = "评论了你的文章";
      } else {
        text = "评论了你的内容";
      }
      break;
    case "REPLY":
      text = "回复了你的评论";
      break;
    case "SYSTEM":
      text = "系统通知";
      break;
    default:
      text = "通知";
  }

  return { text };
};

// 获取通知类型对应的图标和文字
const getTypeInfo = (type: string) => {
  const typeUpper = type.toUpperCase();

  const typeInfoMap: Record<string, { icon: any; text: string }> = {
    FOLLOW: { icon: UserFilled, text: "关注了你" },
    LIKE: { icon: StarFilled, text: "点赞了" },
    COLLECT: { icon: Star, text: "收藏了" },
    COMMENT: { icon: ChatDotRound, text: "评论了" },
    REPLY: { icon: Comment, text: "回复了" },
    SYSTEM: { icon: Setting, text: "系统通知" }
  };

  return typeInfoMap[typeUpper] || { icon: Message, text: "通知" };
};

// 标记组件是否已完成初始化（防止@tab-click在初始化时触发）
const isComponentInitialized = ref(false);
// 记录已访问过的标签页（用于懒加载组件）
const visitedTabs = ref<Set<string>>(new Set());

// 处理选项卡切换
const handleTabChange = (tabName: string) => {
  console.log(`🔔 handleTabChange 被调用，标签页: "${tabName}"`);

  // 保存当前标签页到 localStorage
  localStorage.setItem("message-center-active-tab", tabName);

  // 🔑 清除 URL 中的 from 参数，这样刷新页面后会使用 localStorage 的值
  if (route.query.from) {
    const url = new URL(window.location.href);
    url.searchParams.delete("from");
    window.history.replaceState({}, "", url.toString());
  }

  // 标记为已访问（用于懒加载组件）
  visitedTabs.value.add(tabName);

  // 加载对应标签页的数据
  if (tabName === "interactions") {
    console.log("📊 加载互动消息数据");
    loadNotifications();
  } else if (tabName === "comments") {
    // 评论和回复列表由 CommentReplyList 组件加载
    console.log("📊 加载评论和回复数据");
    // 🔑 使用 nextTick 确保组件已挂载完成
    nextTick(() => {
      commentReplyListRef.value?.loadNotifications?.();
    });
  } else if (tabName === "announcement") {
    console.log("📊 首次加载系统公告数据");
    announcementListRef.value?.loadNotifications?.();
  }
};

// 进入选择模式
const enterSelectionMode = () => {
  selectionMode.value = true;
  selectedGroups.value = [];
  selectAll.value = false;
};

// 退出选择模式
const exitSelectionMode = () => {
  selectionMode.value = false;
  selectedGroups.value = [];
  selectAll.value = false;
};

// 切换选择状态
const toggleSelect = (groupKey: string) => {
  const index = selectedGroups.value.indexOf(groupKey);
  if (index > -1) {
    selectedGroups.value.splice(index, 1);
  } else {
    selectedGroups.value.push(groupKey);
  }

  // 更新全选状态
  selectAll.value =
    selectedGroups.value.length === notificationGroups.value.length;
};

// 全选/取消全选
const handleSelectAll = (checked: boolean) => {
  if (checked) {
    selectedGroups.value = notificationGroups.value.map(g => g.groupKey);
  } else {
    selectedGroups.value = [];
  }
};

// 删除单个通知组(确认后执行)
const confirmDeleteGroup = async (group: GroupedNotification) => {
  try {
    // 获取该组的所有通知ID
    const groupKey = group.groupKey;
    let notificationIds: number[] = [];

    // 如果已经加载过详情,从详情中获取ID
    if (groupDetailsMap.value[groupKey]) {
      notificationIds = groupDetailsMap.value[groupKey].map(d => d.id);
    } else {
      // 否则先加载详情
      const response = await getGroupDetails({
        type: group.type,
        targetType: group.targetType,
        targetId: group.targetId
      });
      if (response.code === 200) {
        notificationIds = response.data.map(d => d.id);
      }
    }

    // 批量删除
    if (notificationIds.length > 0) {
      const deleteResponse = await batchDeleteNotificationsApi(notificationIds);
      if (deleteResponse.code === 200) {
        ElMessage.success("删除成功");

        // 刷新列表和统计
        await loadNotifications();
        await loadStats();
      }
    }
  } catch (error) {
    ElMessage.error("删除失败");
    console.error(error);
  }
};

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedGroups.value.length} 个通知组吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    // 收集所有选中组的通知ID
    const allNotificationIds: number[] = [];

    for (const groupKey of selectedGroups.value) {
      const group = notificationGroups.value.find(g => g.groupKey === groupKey);
      if (!group) continue;

      // 如果已经加载过详情，从详情中获取ID
      if (groupDetailsMap.value[groupKey]) {
        const ids = groupDetailsMap.value[groupKey].map(d => d.id);
        allNotificationIds.push(...ids);
      } else {
        // 否则先加载详情
        const response = await getGroupDetails({
          type: group.type,
          targetType: group.targetType,
          targetId: group.targetId
        });
        if (response.code === 200) {
          const ids = response.data.map(d => d.id);
          allNotificationIds.push(...ids);
        }
      }
    }

    // 执行批量删除
    if (allNotificationIds.length > 0) {
      const response = await batchDeleteNotificationsApi(allNotificationIds);
      if (response.code === 200) {
        ElMessage.success(`已删除 ${allNotificationIds.length} 条通知`);

        // 退出选择模式
        exitSelectionMode();

        // 刷新列表和统计
        await loadNotifications();
        await loadStats();
      }
    }
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
      console.error(error);
    }
  }
};

// 处理公告未读数量更新
const handleUpdateAnnouncementCount = () => {
  // 公告数据变化时，刷新统计数据
  loadStats();
};

// 🔑 已移除：watch(activeTab) 监听器与 handleTabChange 中的 router.replace 重复
// 会导致组件被挂载两次，因此删除此 watch
// handleTabChange 中已经处理了 URL 同步，无需重复监听

// 处理用户点击标签页（只在用户主动点击时触发）
const handleTabClick = (tab: any) => {
  console.log(
    `👆 用户点击标签页: "${tab.paneName}"，组件初始化: ${isComponentInitialized.value}`
  );

  // 🔑 只在组件初始化完成后才处理点击事件
  // 这样可以避免 el-tabs 初始化时触发的点击事件
  if (!isComponentInitialized.value) {
    console.log(`⏭️ 组件未初始化，忽略点击事件`);
    return;
  }

  handleTabChange(tab.paneName as string);
};

// 初始化
onMounted(() => {
  console.log(`🚀 组件 onMounted，当前标签页: "${activeTab.value}"`);

  // 只在页面首次加载时请求一次统计数据
  loadStats();

  // 🔑 先将当前标签页标记为已访问，触发组件渲染
  visitedTabs.value.add(activeTab.value);

  // 🔑 使用 nextTick 确保组件已渲染完成后再加载数据
  nextTick(() => {
    handleTabChange(activeTab.value);

    // 🔑 标记为已初始化，允许筛选器正常工作
    // 必须在 nextTick 内部设置，确保数据加载完成后才允许筛选
    isInitialized.value = true;
  });

  // 🔑 标记为已初始化，允许后续的 @tab-click 事件生效
  isComponentInitialized.value = true;

  // "评论和回复" 标签页的数据由 CommentReplyList 在首次挂载时自行加载
  // 公告页面由 AnnouncementList 组件自己加载
});

onBeforeUnmount(() => {
  console.log(`💀 组件 onBeforeUnmount，即将销毁`);
});
</script>

<style scoped lang="scss">
// 动画
@keyframes float {
  0%,
  100% {
    transform: translateY(0) rotate(0deg);
  }

  50% {
    transform: translateY(-20px) rotate(5deg);
  }
}

// 响应式设计
@media (width <= 1024px) {
  .modern-message-center {
    .message-hero {
      padding: 36px 24px;

      .hero-content {
        flex-direction: column;
        gap: 24px;
        align-items: flex-start;

        .hero-stats {
          width: 100%;

          .stat-card {
            width: 100%;
          }
        }
      }
    }

    .tabs-wrapper {
      padding: 0 24px;
    }
  }
}

@media (width <= 768px) {
  .modern-message-center {
    .message-hero {
      padding: 28px 20px;
      border-radius: 0 0 16px 16px;

      .hero-content {
        .hero-left {
          .hero-title {
            font-size: 28px;

            .title-icon {
              font-size: 32px;
            }
          }

          .hero-subtitle {
            font-size: 14px;
          }
        }

        .hero-stats {
          .stat-card {
            padding: 16px 24px;

            .stat-number {
              font-size: 32px;
            }

            .stat-label {
              font-size: 13px;
            }
          }
        }
      }
    }

    .tabs-wrapper {
      padding: 0 16px;

      .modern-tabs {
        border-radius: 16px;

        :deep(.el-tabs__item) {
          margin-right: 24px;
          font-size: 15px;
        }

        .tab-content-wrapper {
          padding: 16px;
        }
      }
    }

    .filter-section {
      padding: 16px;

      .filter-container {
        gap: 16px;

        .filter-group {
          .filter-pills {
            gap: 8px;

            .filter-pill {
              padding: 8px 14px;
              font-size: 13px;

              .el-icon {
                font-size: 14px;
              }
            }
          }
        }
      }
    }

    .notification-content {
      padding: 16px;
    }

    .notification-item {
      flex-wrap: wrap;
      padding: 12px 16px;

      .item-icon {
        width: 36px;
        height: 36px;
      }

      .item-content {
        flex: 1;
        min-width: 0;

        .content-header {
          flex-wrap: wrap;
          gap: 8px;

          .avatar-group {
            .el-avatar {
              width: 20px !important;
              height: 20px !important;
            }
          }

          .content-title {
            width: 100%;
            font-size: 13px;
          }
        }

        .content-preview {
          .preview-text {
            font-size: 12px;
          }
        }
      }

      .item-aside {
        flex-direction: row;
        justify-content: space-between;
        order: 2;
        width: 100%;
        margin-top: 8px;

        .item-actions {
          opacity: 1;
        }
      }
    }

    .notification-pagination {
      padding: 16px;

      :deep(.el-pagination) {
        .el-pagination__sizes,
        .el-pagination__jump {
          display: none;
        }
      }
    }
  }
}

@media (width <= 480px) {
  .modern-message-center {
    .message-hero {
      padding: 24px 16px;

      .hero-content {
        .hero-left {
          .hero-title {
            font-size: 24px;

            .title-icon {
              font-size: 28px;
            }
          }
        }
      }
    }

    .tabs-wrapper {
      padding: 0 12px;

      .modern-tabs {
        :deep(.el-tabs__nav-wrap) {
          padding: 8px 16px 0;
        }

        :deep(.el-tabs__item) {
          margin-right: 16px;
          font-size: 14px;
        }
      }
    }

    .filter-section {
      padding: 12px;

      .filter-container {
        .filter-group {
          .filter-label {
            font-size: 13px;
          }

          .filter-pills {
            .filter-pill {
              padding: 7px 12px;
              font-size: 12px;
            }
          }
        }
      }
    }

    .notification-content {
      padding: 12px;
    }

    .modern-notification-card {
      .card-main {
        padding: 16px;
      }
    }
  }
}

.modern-message-center {
  max-width: 1400px;
  padding: 24px;
  margin: 0 auto;

  // 顶部横幅
  .message-hero {
    position: relative;
    padding: 48px 32px;
    margin-bottom: 24px;
    overflow: hidden;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 24px;
    box-shadow: 0 8px 32px rgb(102 126 234 / 25%);

    .hero-background {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      pointer-events: none;
      opacity: 0.1;

      .hero-shape {
        position: absolute;
        background: #fff;
        border-radius: 50%;

        &.shape-1 {
          top: -50px;
          right: 10%;
          width: 200px;
          height: 200px;
          animation: float 8s ease-in-out infinite;
        }

        &.shape-2 {
          bottom: -30px;
          left: 15%;
          width: 150px;
          height: 150px;
          animation: float 10s ease-in-out infinite 1s;
        }

        &.shape-3 {
          top: 50%;
          right: 25%;
          width: 100px;
          height: 100px;
          animation: float 12s ease-in-out infinite 2s;
        }
      }
    }

    .hero-content {
      position: relative;
      z-index: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .hero-left {
        .hero-title {
          display: flex;
          gap: 12px;
          align-items: center;
          margin: 0 0 8px;
          font-size: 36px;
          font-weight: 700;
          color: #fff;
          letter-spacing: -0.5px;

          .title-icon {
            font-size: 40px;
          }
        }

        .hero-subtitle {
          margin: 0;
          font-size: 16px;
          color: rgb(255 255 255 / 85%);
        }
      }

      .hero-stats {
        .stat-badge {
          display: inline-flex;
          gap: 8px;
          align-items: center;
          padding: 12px 24px;
          background: rgb(255 255 255 / 25%);
          border-radius: 50px;
          box-shadow: 0 4px 20px rgb(0 0 0 / 15%);
          backdrop-filter: blur(10px);
          transition: all 0.3s ease;

          &:hover {
            background: rgb(255 255 255 / 30%);
            box-shadow: 0 6px 24px rgb(0 0 0 / 20%);
            transform: translateY(-2px);
          }

          .badge-number {
            font-size: 28px;
            font-weight: 700;
            line-height: 1;
            color: #fff;
            text-shadow: 0 2px 8px rgb(0 0 0 / 20%);
          }

          .badge-text {
            font-size: 14px;
            font-weight: 600;
            color: rgb(255 255 255 / 90%);
            white-space: nowrap;
          }
        }
      }
    }
  }

  // 选项卡容器
  .tabs-wrapper {
    padding: 0;

    .modern-tabs {
      background: #fff;
      border-radius: 20px;
      box-shadow: 0 4px 16px rgb(0 0 0 / 6%);

      :deep(.el-tabs__header) {
        padding: 0;
        margin: 0;
        background: transparent;
        border: none;
      }

      :deep(.el-tabs__nav-wrap) {
        padding: 12px 24px 0;

        &::after {
          display: none;
        }
      }

      :deep(.el-tabs__nav) {
        border: none;
      }

      :deep(.el-tabs__item) {
        padding: 16px 0;
        margin-right: 40px;
        font-size: 16px;
        font-weight: 600;
        color: #64748b;
        border: none;
        transition: all 0.3s ease;

        &:hover {
          color: #667eea;
        }

        &.is-active {
          color: #667eea;
        }
      }

      :deep(.el-tabs__active-bar) {
        background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        border-radius: 2px;
      }

      .tab-label {
        display: flex;
        gap: 8px;
        align-items: center;

        .tab-icon {
          font-size: 18px;
          transition: transform 0.3s ease;
        }

        .tab-text {
          font-size: 16px;
        }

        .tab-count {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          min-width: 20px;
          padding: 2px 6px;
          margin-left: 2px;
          font-size: 11px;
          font-weight: 700;
          line-height: 1;
          color: #fff;
          background: linear-gradient(135deg, #f43f5e 0%, #dc2626 100%);
          border-radius: 10px;
          box-shadow: 0 2px 6px rgb(244 63 94 / 35%);
          transition: all 0.3s ease;
        }
      }

      // 激活状态下的样式
      :deep(.el-tabs__item.is-active) {
        .tab-icon {
          transform: scale(1.1);
        }

        .tab-count {
          color: #667eea;
          background: #fff;
          box-shadow: 0 2px 8px rgb(102 126 234 / 35%);
        }
      }

      // 鼠标悬停效果
      :deep(.el-tabs__item:hover) .tab-count {
        transform: scale(1.05);
      }

      // 标签页内容
      .tab-content-wrapper {
        padding: 0;
      }
    }
  }

  // 筛选区域
  .filter-section {
    padding: 24px;
    background: #fff;

    .filter-container {
      display: flex;
      flex-direction: row;
      gap: 32px;
      align-items: flex-start;

      .filter-group {
        display: flex;
        flex-direction: column;
        gap: 4px;

        .filter-label {
          margin-bottom: 8px;
          font-size: 14px;
          font-weight: 600;
          color: #334155;
        }

        .filter-buttons {
          display: flex;
          flex-wrap: wrap;
          gap: 4px;

          .el-button {
            border-radius: 8px;
            transition: all 0.3s ease;

            .el-icon {
              margin-right: 4px;
              font-size: 16px;
            }

            &:hover {
              transform: translateY(-2px);
            }

            .status-dot {
              display: inline-block;
              width: 8px;
              aspect-ratio: 1;
              margin-right: 6px;
              border-radius: 50%;

              &.unread {
                background: #10b981;
                box-shadow: 0 0 8px rgb(16 185 129 / 60%);
              }

              &.read {
                background: #94a3b8;
              }
            }

            // 通知数量角标
            .count-badge {
              display: inline-flex;
              align-items: center;
              justify-content: center;
              min-width: 18px;
              padding: 2px 5px;
              margin-left: 6px;
              font-size: 11px;
              font-weight: 700;
              line-height: 1;
              color: #fff;
              background: linear-gradient(135deg, #f43f5e 0%, #dc2626 100%);
              border-radius: 9px;
              box-shadow: 0 2px 6px rgb(244 63 94 / 35%);
            }

            // 激活状态下的角标
            &.el-button--primary .count-badge {
              color: #667eea;
              background: #fff;
              box-shadow: 0 2px 6px rgb(0 0 0 / 15%);
            }
          }

          .filter-badge {
            margin-left: 4px;

            :deep(.el-badge__content) {
              padding: 2px 5px;
              font-size: 11px;
              line-height: 1;
              border: none;
            }
          }
        }
      }
    }
  }

  // 批量操作工具栏
  .batch-actions-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 24px;
    background: #fff;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;

    .actions-left {
      display: flex;
      gap: 16px;
      align-items: center;

      .result-count {
        font-size: 14px;
        color: #4e5969;

        strong {
          font-weight: 600;
          color: #1d2129;
        }

        .unread-count {
          color: #ff7a45;
        }
      }

      .selected-count {
        font-size: 14px;
        color: #4e5969;

        strong {
          font-weight: 600;
          color: #1677ff;
        }
      }
    }

    .actions-right {
      display: flex;
      gap: 12px;

      .el-button {
        font-weight: 500;
        transition: all 0.3s ease;

        &:hover {
          box-shadow: 0 4px 12px rgb(102 126 234 / 25%);
          transform: translateY(-1px);
        }
      }
    }
  }

  // 通知列表区域 - 排行榜风格
  .notification-list {
    padding: 20px;
    background: #fff;
  }

  // 通知项容器(包含主行和展开详情)
  .notification-item-wrapper {
    border-bottom: 1px solid #f2f3f5;

    &:last-child {
      border-bottom: none;
    }
  }

  // 列表项 - 排行榜风格
  .notification-item {
    display: flex;
    align-items: center;
    padding: 12px 0;
    cursor: pointer;
    transition: all 0.2s ease;

    &:hover:not(.selection-mode) {
      padding-right: 12px;
      padding-left: 12px;
      background: #f8fafc;
      border-radius: 6px;
      box-shadow: 0 2px 8px rgb(0 0 0 / 5%);
      transform: translateX(2px);
    }

    &.selection-mode {
      padding-left: 0;

      &:hover {
        background: #f5f7fa;
        border-radius: 6px;
      }
    }

    &.is-unread {
      .content-header .content-title {
        font-weight: 600;
        color: #1d2129 !important;
      }
    }

    // 复选框容器
    .item-checkbox {
      display: flex;
      align-items: center;
      padding: 0 12px;
      margin-right: 8px;

      .el-checkbox {
        :deep(.el-checkbox__inner) {
          width: 18px;
          aspect-ratio: 1;
        }

        :deep(.el-checkbox__label) {
          display: none;
        }
      }
    }

    // 左侧图标 - 排行榜风格
    .item-icon {
      position: relative;
      flex-shrink: 0;
      width: 36px;
      margin-right: 12px;

      .icon-wrapper {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 36px;
        aspect-ratio: 1;
        border-radius: 50%;
        transition: all 0.2s ease;

        &.icon-like {
          color: #ff7a45;
          background: #fff7e6;
        }

        &.icon-comment {
          color: #1677ff;
          background: #e6f7ff;
        }

        &.icon-reply {
          color: #722ed1;
          background: #f9f0ff;
        }

        &.icon-follow {
          color: #52c41a;
          background: #f6ffed;
        }

        &.icon-system {
          color: #8a919f;
          background: #f5f6f7;
        }
      }

      .unread-dot {
        position: absolute;
        top: -2px;
        right: -2px;
        width: 8px;
        aspect-ratio: 1;
        background: #ff4d4f;
        border: 2px solid #fff;
        border-radius: 50%;
      }
    }

    // 中间内容 - 排行榜风格
    .item-content {
      flex: 1;
      min-width: 0;
      overflow: hidden;

      .content-header {
        display: flex;
        gap: 10px;
        align-items: center;
        margin-bottom: 4px;

        .avatar-group {
          display: flex;
          align-items: center;

          .el-avatar {
            border: 2px solid #fff;
            box-shadow: 0 1px 2px rgb(0 0 0 / 10%);
          }
        }

        .content-title {
          flex: 1;
          min-width: 0;
          overflow: hidden;
          text-overflow: ellipsis;
          font-size: 14px;
          line-height: 1.5;
          color: #94a3b8;
          white-space: nowrap;
          transition: color 0.2s ease;
        }

        .count-badge {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          min-width: 20px;
          padding: 2px 6px;
          font-size: 11px;
          font-weight: 700;
          line-height: 1;
          color: #fff;
          background: linear-gradient(135deg, #f43f5e 0%, #dc2626 100%);
          border-radius: 10px;
          box-shadow: 0 2px 6px rgb(244 63 94 / 30%);
        }
      }

      .content-preview {
        .preview-text {
          display: block;
          overflow: hidden;
          text-overflow: ellipsis;
          font-size: 12px;
          line-height: 1.5;
          color: #8a919f;
          white-space: nowrap;
        }
      }

      // 操作提示
      .action-hint {
        display: inline-flex;
        gap: 4px;
        align-items: center;
        padding: 4px 8px;
        margin-top: 4px;
        font-size: 12px;
        font-weight: 500;
        color: #1677ff;
        cursor: pointer;
        user-select: none;
        background: #f0f5ff;
        border-radius: 4px;
        transition: all 0.2s ease;

        .el-icon {
          font-size: 12px;
          transition: transform 0.2s ease;
        }

        &:hover {
          color: #0958d9;
          background: #e6f4ff;
          transform: translateX(2px);

          .el-icon {
            transform: translateX(2px);
          }
        }

        &:active {
          transform: translateX(1px);
        }
      }
    }

    // 右侧信息 - 排行榜风格
    .item-aside {
      display: flex;
      flex-shrink: 0;
      gap: 8px;
      align-items: center;
      width: 280px;
      margin-left: auto;

      .item-time {
        width: 80px;
        font-size: 12px;
        color: #8a919f;
        text-align: right;
        white-space: nowrap;
      }

      .item-actions {
        display: flex;
        gap: 4px;
        align-items: center;
        justify-content: flex-end;
        width: 160px;

        .read-text {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          min-width: 48px;
          padding: 4px 12px;
          font-size: 12px;
          color: #94a3b8;
          background: #f8fafc;
          border-radius: 4px;
        }

        .el-button {
          padding: 4px 8px;
          font-size: 12px;
          color: #8a919f;
          transition: all 0.2s ease;

          &:hover {
            color: #1677ff;
            background: #f0f5ff;
          }

          &.el-button--danger:hover {
            color: #ff4d4f;
            background: #fff1f0;
          }

          .el-icon {
            font-size: 14px;
          }
        }
      }
    }

    &:hover {
      .item-content .content-header .content-title {
        color: #1677ff;
      }
    }

    // 卡片头部 (保留以下的样式以兼容展开详情)
    .card-header {
      position: relative;
      z-index: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;

      .header-left {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        align-items: center;

        .el-tag {
          display: inline-flex !important;
          gap: 5px;
          align-items: center !important;
          justify-content: center;
          padding: 4px 12px !important;
          font-size: 13px !important;
          font-weight: 600 !important;
          line-height: 1 !important;
          border-radius: 8px !important;

          .el-icon {
            display: flex;
            align-items: center;
            margin: 0;
            font-size: 14px !important;
          }
        }
      }

      .header-right {
        .notification-time {
          font-size: 13px;
          font-weight: 500;
          color: #94a3b8;
          white-space: nowrap;
        }
      }
    }

    // 卡片主体
    .card-body {
      position: relative;
      z-index: 1;
      margin-bottom: 16px;
      cursor: pointer;
      transition: all 0.2s ease;

      &:hover {
        .notification-title {
          color: #667eea;
        }
      }
    }

    // 头像区域
    .avatars-section {
      display: flex;
      gap: 12px;
      align-items: center;
      margin-bottom: 16px;

      .avatar-stack {
        display: flex;
        align-items: center;

        .sender-avatar {
          border: 3px solid #fff;
          box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
          transition: all 0.3s ease;

          &:hover {
            z-index: 10 !important;
            box-shadow: 0 4px 16px rgb(0 0 0 / 20%);
            transform: scale(1.15);
          }
        }
      }

      .more-text {
        padding: 4px 10px;
        font-size: 13px;
        font-weight: 600;
        color: #667eea;
        background: linear-gradient(135deg, #eef2ff 0%, #e0e7ff 100%);
        border-radius: 12px;
      }
    }

    // 通知标题
    .notification-title {
      margin-bottom: 12px;
      font-size: 18px;
      font-weight: 700;
      line-height: 1.5;
      color: #1e293b;
      transition: color 0.3s;
    }

    // 目标内容
    .target-content {
      padding: 12px;
      background: #f8fafc;
      border-left: 3px solid #667eea;
      border-radius: 4px;

      .target-title {
        margin-bottom: 6px;
        font-size: 14px;
        font-weight: 600;
        color: #667eea;
      }

      .target-summary {
        display: -webkit-box;
        overflow: hidden;
        text-overflow: ellipsis;
        -webkit-line-clamp: 2;
        font-size: 13px;
        line-height: 1.6;
        color: #64748b;
        -webkit-box-orient: vertical;
      }
    }

    // 卡片底部
    .card-footer {
      position: relative;
      z-index: 1;
      display: flex;
      gap: 10px;

      .el-button {
        font-size: 13px;
        font-weight: 600;
        border-radius: 10px;
        transition: all 0.3s ease;

        &.el-button--primary {
          color: #fff;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          border: none;

          &:hover {
            box-shadow: 0 4px 12px rgb(102 126 234 / 40%);
            transform: translateY(-2px);
          }
        }

        &:not(.el-button--primary) {
          color: #64748b;
          background: #f8fafc;
          border: 1px solid #e2e8f0;

          &:hover {
            color: #667eea;
            background: #eef2ff;
            border-color: #667eea;
          }
        }
      }
    }
  }
}

// 展开的详情区域
.group-details {
  padding: 20px 16px 16px 48px;
  background: #f8fafc;
  border-radius: 0 0 8px 8px;
  transition: all 0.3s ease;

  // 目标内容卡片
  .target-content-card {
    padding: 16px;
    margin-bottom: 16px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgb(0 0 0 / 4%);

    .target-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;

      .target-label {
        display: flex;
        gap: 6px;
        align-items: center;

        .target-icon {
          font-size: 16px;
          color: #667eea;
        }

        .target-type-text {
          font-size: 13px;
          font-weight: 600;
          color: #64748b;
        }
      }
    }

    .target-content {
      display: flex;
      flex-direction: column;
      gap: 12px;

      // 新评论/回复内容
      .new-comment {
        display: flex;
        gap: 4px;
        align-items: flex-start;
        padding: 10px 12px;
        background: #f0f5ff;
        border-left: 3px solid #667eea;
        border-radius: 4px;

        .comment-prefix {
          flex-shrink: 0;
          font-size: 13px;
          font-weight: 500;
          color: #667eea;
        }

        .comment-text {
          flex: 1;
          font-size: 13px;
          line-height: 1.6;
          color: #252933;
          word-break: break-word;
        }
      }

      // 原内容
      .original-content {
        display: flex;
        gap: 6px;
        align-items: flex-start;
        padding: 10px 12px;
        background: #f8fafc;
        border-radius: 4px;

        .content-icon {
          flex-shrink: 0;
          margin-top: 2px;
          font-size: 14px;
          color: #8a919f;
        }

        .content-text {
          flex: 1;
          font-size: 13px;
          font-weight: 500;
          line-height: 1.6;
          color: #64748b;
          word-break: break-word;
        }
      }
    }
  }

  // 详情列表头部
  .details-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 12px 12px;
    border-bottom: 2px solid #e5e6eb;

    .details-title {
      font-size: 14px;
      font-weight: 600;
      color: #252933;
    }

    .details-count {
      font-size: 13px;
      color: #8a919f;
    }
  }

  // 用户列表
  .user-list {
    padding: 0;
    margin: 0;

    .user-item {
      padding: 12px;
      border-bottom: 1px solid #e5e6eb;
      transition: all 0.2s ease;

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background: #fff;
        border-radius: 6px;
        box-shadow: 0 2px 8px rgb(0 0 0 / 4%);
        transform: translateX(4px);
      }

      &.is-unread {
        background: #fff;
        border-radius: 6px;

        .user-name {
          font-weight: 600;
          color: #252933;
        }
      }

      .item-left {
        display: flex;
        gap: 12px;
        align-items: center;

        .user-avatar {
          flex-shrink: 0;
          border: 2px solid #fff;
          box-shadow: 0 2px 6px rgb(0 0 0 / 8%);
          transition: all 0.2s ease;

          &:hover {
            box-shadow: 0 4px 12px rgb(0 0 0 / 15%);
            transform: scale(1.05);
          }
        }

        .message-user-content {
          flex: 1;
          min-width: 0;

          .user-header {
            display: flex;
            gap: 8px;
            align-items: center;
            margin-bottom: 6px;

            .user-name {
              font-size: 14px;
              font-weight: 500;
              color: #252933;
              transition: color 0.2s ease;

              &:hover {
                color: #667eea;
                cursor: pointer;
              }
            }

            .user-action {
              font-size: 13px;
              color: #8a919f;
            }

            .meta-time {
              margin-left: auto;
              font-size: 12px;
              color: #8a919f;
              white-space: nowrap;
            }

            .el-tag {
              font-size: 11px;
              font-weight: 600;
              border-radius: 4px;
            }
          }

          .comment-content {
            padding: 8px 12px;
            margin-top: 4px;
            font-size: 13px;
            line-height: 1.6;
            color: #64748b;
            background: #f8fafc;
            border-left: 3px solid #667eea;
            border-radius: 4px;
          }
        }
      }
    }
  }
}

// 展开/收起动画
.slide-fade-enter-active {
  transition: all 0.3s ease;
}

.slide-fade-leave-active {
  transition: all 0.3s ease;
}

.slide-fade-enter-from {
  opacity: 0;
  transform: translateY(-10px);
}

.slide-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

// 分页
.notification-pagination {
  display: flex;
  justify-content: center;
  padding: 24px;
  background: #fff;

  :deep(.el-pagination) {
    .el-pager li {
      border-radius: 6px;
    }

    .btn-prev,
    .btn-next {
      border-radius: 6px;
    }
  }
}
</style>
